# LuckPay Web Manage System
#
# Copyright (c) 2016 Lucky Byte, Inc.
#
express = require 'express'
pgsql   = require 'pg'
uuid    = require 'uuid'
moment  = require 'moment'
router = express.Router()
module.exports = router


router.all '/', (req, res, next) ->
    where_clause = """(
        r.uuid like $1 or
        case
        when t1.chnl in (1,2,4) then
            json_extract_path_text(t1.i_pkt, '42') like $1 or
            json_extract_path_text(t1.i_pkt, '41') like $1 or
            json_extract_path_text(t1.i_pkt, '4')  like $1 or
            json_extract_path_text(t1.i_pkt, '11') like $1
        end
    )"""

    today = moment().format('YYYY-MM-DD')

    # 如果没有提供日期，则仅查询当日
    start_date = req.body.start_date or req.query.start_date or today
    end_date = req.body.end_date or req.query.end_date or today

    table_name = 'pay_trlist_hist'
    if start_date is today and end_date is today
        table_name = 'pay_trlist'

    where_clause += " and r.ctime::date >= '#{start_date}'"
    res.locals.start_date = start_date
    where_clause += " and r.ctime::date <= '#{end_date}'"
    res.locals.end_date = end_date

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    await client.query "select count(*)::int as count
        from pay_t40_recvr as r
        left join #{table_name} as t1 on
            t1.uuid = r.tr_uuid_1 and t1.incoming = true
        where #{where_clause} and r.checked = true", [
            '%' + res.locals.keyword + '%'
        ], defer err, result
    if err then done(client); return next(err)
    res.locals.total = result.rows[0].count

    await client.query "select r.*,
        t1.sys_time as tr1_systime,
        json_extract_path_text(t1.merch, 'name') as tr1_mername,
        case
        when t1.chnl in (1,2,4) then
            array[
                json_extract_path_text(t1.i_pkt, '42'),
                json_extract_path_text(t1.i_pkt, '41'),
                json_extract_path_text(t1.i_pkt, '4'),
                json_extract_path_text(t1.i_pkt, '11')]
        end as tr1_info,
        u.realname as input_user, u2.realname as check_user
        from pay_t40_recvr as r
        left join #{table_name} as t1 on
            t1.uuid = r.tr_uuid_1 and t1.incoming = true
        left join web_users as u on u.uuid = r.inputer
        left join web_users as u2 on u2.uuid = r.checker
        where #{where_clause} and r.checked = true
        order by r.serial desc offset $2 limit $3",[
            '%' + res.locals.keyword + '%'
            res.locals.offset, res.locals.page_rows
        ], defer err, result
    if err then done(client); return next(err)
    done()

    res.locals.records = result.rows
    res.render 't40_recvr/done'
